//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');

var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');


var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');


var goodOrders = new Array();
var createTime = util.formatTime(new Date()).toString();

var goodsType = "jd";
var orderType_z = "zonghe";         //综合排序
var orderType_t = "totalSalesDesc"; //销量排序
var orderType_c = "couponMoneyDesc";   //优惠券排序

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: false,   //是否显示面板指示点（轮播图）
    autoplay: true,        //是否自动切换（轮播图）
    interval: 6000,         //自动切换时间间隔（轮播图）
    duration: 1000,         //滑动动画时长（轮播图）
    specliGoods:[],         //特卖商品集合
    jdGoodsList : [],       //京东商品集合
    JdListLength:'10',      //京东商品集合长度
    JdListStart : '0',      //京东商品集合开始
    orderTypeNum : '1',     //京东商品排序方式
    openId : '',
    currentTab : '0',
    carts :'0',
    showCancelArea : false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var openId = wx.getStorageSync('openId');     //用户openId获取
    var phone = wx.getStorageSync('phone');       //用户phone获取
    var userId = wx.getStorageSync('userId');     //用户userId获取
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取


    if (openId != '') {
      that.setData({
        openId: openId,
        showCancelArea: false
      });
    }else{
      that.setData({
        showCancelArea: true
      });
    }

    /**
     * 判断是否有手机号
     */
    if (phone == '') {
      that.setData({
        phone: ''
      })
    } else {
      that.setData({
        phone: phone
      })
      that.gucl();
    }

    if (userId != '') {
      that.setData({
        userId: userId
      });
    }

    if (userInfo != '') {
      that.setData({
        userInfo: userInfo
      });
    }

    that.shopDetail();                  //商家详情
    that.getTabType();
    that.countSpecliHeight();           //特卖内容
    that.getSpecliGoods();
    that.getactivity();                 //三个广告位

    //商品详情
    
    var spuId = options.spuId;
    console.log(spuId)
    if (spuId != undefined){
      that.alertDetail(spuId)
    }

    //window 高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
        });
      }
    });
    wx.showTabBar({
      aniamtion: true,
    })
  },
  /**
   * 手机号授权方式
   */
  getPhoneNumberF : function(res){
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }else{
      wx.showToast({
        title: '授权后即可购买',
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },

  /**
  * 解密用户登录完成后的url (用户手机号)
  */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;
          that.setData({
            phone: phone
          })

          wx.setStorageSync('phone', phone);
          that.reginPhoneOpenid(phone);
        } else {
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //表单提交
  reginPhoneOpenid: function (userPhone) {
    var that = this;

    var nickName = that.data.userInfo.nickName;     //	昵称
    var avatarUrl = that.data.userInfo.avatarUrl;   //用户头像
    var gender = that.data.userInfo.gender;         //性别1为男，0为女
    var city = that.data.userInfo.city;             //城市
    var country = that.data.userInfo.country;       //国家
    var province = that.data.userInfo.province;     //省

    wx.request({
      url: apiHost + "xcx/login/reg",
      data: {
        // openId: 'olGet4mNKn1FeKEvSrGiMuY6v3ZB',
        openId: that.data.openId,
        yunId: yunId,
        userPhone: userPhone,
        nickName: nickName,
        avatarUrl: avatarUrl,
        gender: gender,
        city: city,
        country: country,
        province: province
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == '10004') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: res.data.msg
          })
        }
        if (res.data.code == '10000') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: '　'
          })
        } else {
          that.setData({
            is_code: (!that.data.is_phone),   //提示信息
            ts_msg: res.data.msg
          })
        }
      },
    });

  },
  //获取排序方式
  getOrderTyep:function(orderNum){
    switch (orderNum) {
      case '1':
        return orderType_z;
        break;
      case '2':
        return orderType_t;
        break;
      case '3':
        return orderType_c;
        break;
    }
  },

  //获取tab页类型
  getTabType: function () {
    var that = this;
    wx.request({
      url: apiHost + "/xcx/banner/type/list",
      data: {
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code
        var msg = res.data.msg
        
        if (code = "10000") {
          var typeList = res.data.data;
          that.getbanner(typeList[0].type);                   //获取轮播图
          that.setData({
            tabTypeList: typeList
          })
        } else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },


  //获取轮播图
  getbanner: function (banType) {
    var that = this;

    wx.request({
      url: apiHost + "/xcx/banner/list",
      data: {
        yunId: yunId,
        openId: that.data.openId,
        'type': banType
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code
        var msg = res.data.msg

        if (code=="10000"){
          var banners = res.data.data;
          var imgUrls = [];
          // 轮播图集合 push
          for (var i = 0; i < banners.length; i++) {
            imgUrls.push(banners[i].image)
          }

          that.setData({
            imgUrls: imgUrls
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  //特卖商品
  getSpecliGoods:function(){
    var that = this;
    // 微信请求（点击分类）
    wx.request({
      url: apiHost + "xcx/goods/list/condition",
      data: {
        yunId: yunId,
        openId: that.data.openId,
        isSpecial: '1'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code
        var msg = res.data.msg

        if (code=="10000"){
          var specliGoodsList = res.data.data.list;
          // 特卖商品集合
          that.setData({
            specliGoods: specliGoodsList
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
    });
  },
  //商家详情
  shopDetail: function () {
    var that = this;

    //商家
    wx.request({
      url: apiHost + "/xcx/store/detail",
      data: {
        yunId: yunId,
        userId: that.data.userId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code
        var msg = res.data.msg

        if (code=="10000"){
          that.setData({
            shangjiadizhi: res.data.data.address,
            tel: res.data.data.phone,
            deliveryTimeType: res.data.data.deliveryTimeType,
            deliveryCost: res.data.data.deliveryCost,
            deliveryFee: res.data.data.deliveryFee,
            outCostFree: res.data.data.outCostFree,
            state: res.data.data.state,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      }
    })
  },

  //初始化购物车
  gucl: function (e) {
    var that = this;

    //购物车列表
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/list",
      data: {
        yunId: yunId,
        openId: that.data.openId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var countCarts = 0;
        var code = res.data.code;
        var msg = res.data.msg;

        if (code=="10000"){
          var CartsList = res.data.data.list;
          //循环遍历所有购物车的数量
          for (var a = 0; a < CartsList.length; a++) {
            countCarts += CartsList[a].count
          }
          that.setData({
            gwclist: CartsList,
            carts: countCarts
          });

          //总价
          var newList = that.data.gwclist
          var newaa = 0
          for (var i = 0; i < newList.length; i++) {
            newaa += newList[i].count * newList[i].price
          }

          that.setData({
            zong: newaa.toFixed(2),
          })
          that.getSpecliGoods();
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })

  },
  // 购物车的显示隐藏
  cart: function (e) {
    var that = this;
    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = bianjidizhiList[2];

    that.setData({
      textId: spuId
    })

    that.setData({
      num: 1
    })
    that.gucl();
    var count = that.data.num
    that.addCart(spuId, count)

  },
  // 数量的++
  add: function (e) {
    var that = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);

    var index = parseInt(e.target.dataset.index);
    that.setData({
      showModal: false,
      showModall: true,
      num: num + 1,
    })

    var count = that.data.num
    that.addCart(spuId, count);//计算购物车数量
  },
  //隐藏购物车的++
  addd: function (e) {
    var that = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");     //以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)

    that.setData({
      numm: parseInt(count) + 1,
    })
    var count = that.data.numm
    that.addCart(spuId, count);//计算购物车数量

  },
  /**
   * 计算购物车数量
   */
  addCart: function (spuId, count) {
    var that = this
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
   
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/add",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        spuId: spuId,
        count: count
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.gucl();
          that.getSpecliGoods();
          wx.hideLoading();   //隐藏加载loading
        }else{
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  // 数量的--
  minus: function (e) {
    var that = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);
    var cartId = bianjidizhiList[3];

    that.setData({
      num: num - 1,
    })
    var count = that.data.num

    if (count == 0) {
      that.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
    } else {
      that.addCart(spuId, count);//计算购物车数量
    }
  },
  //隐藏购物车的--
  minuss: function (e) {
    var that = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");//以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var cartId = gouList[3];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)
    that.setData({
      numm: parseInt(count) - 1,
    })
    var count = that.data.numm

    if (count == 0) {
      that.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
    } else {
      that.addCart(spuId, count);//计算购物车数量
    }
  },

  
  //删除购物车（当前商品在购物车）
  removeShopCart: function (cartId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
   
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/del",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        cartId: cartId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.gucl();
          that.getSpecliGoods();
          wx.hideLoading();   //隐藏加载loading
        }else{
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  //打开购物车
  gouwuchez: function () {
    var that = this
    that.setData({
      showModalll: true
    })

  },
  //关闭购物车
  gouwuchezz: function () {
    var that = this
    that.setData({
      showModalll: false
    })
  },
  // 清空购物车
  qingkong: function () {
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/clear",
      data: {
        openId: that.data.openId,
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          // console.log(res)
          that.gucl();
          wx.hideLoading();   //隐藏加载loading
        }else{
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  //结算
  settlement: function () {
    var that = this
    var newList = that.data.gwclist
    var a = ''
    var json = '';
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    goodOrders = new Array();
    for (var i = 0; i < newList.length; i++) {
      a = {
        spuId: newList[i].spuId,
        count: newList[i].count
      }
      goodOrders.push(a);
    }
    json = JSON.stringify(goodOrders);

    if (goodOrders.length > 0) {
      wx.navigateTo({
        url: '/pages/userOrder/confirm/confirm?goodOrders=' + json + "&yunId=" + yunId + "&openId=" + that.data.openId + "&createTime=" + createTime,
      })
      that.setData({
        goodOrders: json
      })
    }

    that.setData({
      hiddenLoading: true
    });

  },

  /**
   * 获取广告位
   */
  getactivity : function(){
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/jd/activitys",
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var activitysLsit = res.data.data;
          
          that.setData({
            activitysLsit: activitysLsit
          })
          
        } else {

          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },


  /**
   * 获取每日必推商品
   */
  getJdjinxuan: function (start, length) {
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/everyday/jinxuan",
      data: {
        start: start,
        length: length
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var jdList = res.data.data.list;

          var jdGoodsListss = that.data.jdGoodsList;

          // 追加数据
          for (var i = 0; i < jdList.length; i++) {
            jdGoodsListss.push(jdList[i])
          }

          that.setData({
            jdGoodsList: jdGoodsListss
          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  

  /**
   * 获取京东商品集合
   */
  getJdGoodsList : function(start,length,orderTypea){
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({  
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost+"mobile/goods/list",
      data: {
        'type': goodsType,
        start: start,
        length: length,
        orderType : orderTypea
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code=="10000"){
          var jdList = res.data.data.list;
          var jdGoodsListss = that.data.jdGoodsList;

          // 追加数据
          for (var i = 0; i < jdList.length; i++) {
            jdGoodsListss.push(jdList[i])
          }

          that.setData({
            jdGoodsList: jdGoodsListss
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  //计算首页特卖商品 高度
  countSpecliHeight: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var shopHeight = "";

    query2.select('#Ztab').boundingClientRect()
    query2.exec(function (res) {
      shopHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            specliHeight: res.windowHeight  - shopHeight,
          });
        }
      });
    });
  },

  //计算 福礼汇 
  countDFlh: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var bannerCon = "";

    query2.select('#banner_con').boundingClientRect()
    query2.exec(function (res) {
      bannerCon = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            FlhHeight: res.windowHeight - bannerCon,
          });
        }
      });
    });
  },

  //获取高度
  jdGoodsHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var query3 = wx.createSelectorQuery();
    var ZtabHeight = "";
    var sortCon = "";
    // query2.select('#sortCon').boundingClientRect()
    // query2.exec(function (res) {
    //   sortCon = res[0].height;
    // });
    
    query3.select('#Ztab').boundingClientRect()
    query3.exec(function (res) {
      ZtabHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            jdGoodsHeght: res.windowHeight  - ZtabHeight
          });
        }
      });
    });
  },

  //排序
  roderP:function(e){
    var that = this;
    var orderT = e.target.dataset.toggle;
    var lengthflag = that.data.JdListLength;
    var startFlag = that.data.JdListStart;
    if (startFlag=="0"){
      startFlag='1';
    }

    var length = parseInt(lengthflag) * parseInt(startFlag);
    that.setData({
      orderTypeNum: orderT
    })

    var orderType = that.getOrderTyep(orderT);

    that.orderGoodsList('0', length, orderType); //京东优惠商品list

  },

  //排序京东商品列表
  orderGoodsList: function (start, length, orderType){
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost +"mobile/goods/list",
      data: {
        'type': goodsType,
        start: start,
        length: length,
        orderType: orderType
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          var jdList = res.data.data.list;

          wx.hideLoading();   //隐藏加载loading

          that.setData({
            jdGoodsList: jdList
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      }
    })
  },

  //滚动到底部触发事件  
  searchScrollLower: function () {
    var that = this;
    var length = that.data.JdListLength;
    var startFlag = that.data.JdListStart;
    var orderT = that.data.orderTypeNum;
    var nowStart = parseInt(startFlag) + 1

    var orderType = that.getOrderTyep(orderT);

    that.setData({
      JdListStart: nowStart
    });


    // that.getJdGoodsList(nowStart, length, orderType); //京东优惠商品list

    that.getJdjinxuan(nowStart, length); //京东优惠商品list


  },
  //跳转商品详情
  goJdDetail : function(e){
    var that = this;
    var spuId = e.currentTarget.dataset.toggle;

    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.navigateTo({
      url: '../jdDetails/jdDetails?spuId=' + spuId,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },  
    });
  },


  //获取二合一转链
  getUrl: function (spuId){
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost +"xcx/goods/getUrl",
      data: {
        spuId:spuId,
        yunId : yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code  = res.data.code;
        var msg = res.data.msg;

        if(res.data.code=="10000"){
          var jdUrl = res.data.data;

          if (jdUrl==''){
              wx.showToast({
                title:  "红包卷已抢空" ,
                icon: 'none',
                duration: 2000,
                mask:true
              });
          }else{
            var strs = jdUrl.split("?");

            var url = strs[0]
            var param = strs[1]

            var paramBoj = param.split("=");
            var param2 = paramBoj[0];
            var param3 = paramBoj[1];         

            //跳转京东详情
            wx.navigateTo({
              url: '../out/out?jdUrl=' + url + "&param2=" + param2 + "&param3=" + param3
            });
            wx.hideLoading();   //隐藏加载loading
          }
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
          wx.hideLoading();   //隐藏加载loading
        }
      }
    })
  },


  /** 
     * 滑动切换tab 
     */
  bindChange: function (e) {
    var that = this;
    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.target.dataset.current; //获取当前tab页数

    var length = that.data.JdListLength;          //查询长度
    var Start = that.data.JdListStart;            //查询开始
    var orderNum = that.data.orderTypeNum;        //点击
    var orderType = that.getOrderTyep(orderNum);  //筛选条件

    //  重新设置tab 页数
    that.setData({ currentTab: e.detail.current });

    if (currIndex == cateGorytab) {
      that.countSpecliHeight();           //特卖内容
      that.getSpecliGoods();              //特卖商品
    } else if (currIndex == feekbacTab) {

      var length = that.data.JdListLength;
      var Start = that.data.JdListStart;
      var orderNum = that.data.orderTypeNum;
      var orderType = that.getOrderTyep(orderNum);

      // that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
      that.jdGoodsHeght();                //京东优惠商品高度

      that.getJdjinxuan(Start, length); //京东优惠商品list

    } else if (currIndex == shopSetUptab) {
      that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
      that.countDFlh();                 //京东优惠商品高度
    }
  },

  /** 
   * 
   * 点击tab切换 
   */
  swichNav: function (e) {
    var that = this;

    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.target.dataset.current  //获取当前tab页数


    var length = that.data.JdListLength;          //查询长度
    var Start = that.data.JdListStart;            //查询开始
    var orderNum = that.data.orderTypeNum;        //点击
    var orderType = that.getOrderTyep(orderNum);  //筛选条件

    var banType = e.currentTarget.dataset.toggle //获取当前tab页数

    that.getbanner(banType);      //根据类型回去banner


    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      if (currIndex == cateGorytab) {
        that.countSpecliHeight();           //特卖内容
        that.getSpecliGoods();              //特卖商品
      } else if (currIndex == feekbacTab) {
        // that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
        that.jdGoodsHeght();                //京东优惠商品高度
        that.getJdjinxuan(Start, length); //京东优惠商品list

      } else if (currIndex == shopSetUptab) {
        that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
        that.countDFlh();                //京东优惠商品高度
        that.jdGoodsHeght();                //京东优惠商品高度
      }
    }
    //  重新设置tab 页数
    that.setData({
      currentTab: e.target.dataset.current
    });
  },

  //获取随机串  
  createNonceStr : function () {
    return Math.random().toString(36).substr(2, 15);
  },
      
  // timestamp  
  createTimeStamp : function () {
    return parseInt(new Date().getTime() / 1000) + '';
  },   

  //跳转友惠特卖
  toYhspecial: function (e) {

    var id = e.currentTarget.dataset.toggle;

    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.navigateTo({
      url: '../yhSpecial/yhSpecial?id=' + id,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },
  //点击商品，弹出商品详情
  goodsDetail: function (e) {
    var that = this;

    var spuId = e.currentTarget.dataset.toggle;

    that.alertDetail(spuId);//获取弹出商品详情

  },
  /**
   * 获取弹出商品详情
   */
  alertDetail: function (spuId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    wx.request({
      url: apiHost + "/xcx/goods/alert/detail",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        spuId: spuId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg;

        if(code=="10000"){
          var GodDetail = res.data.data
          that.setData({
            goodsDetails: GodDetail,
            goodsDetails_num: GodDetail.shopCartCount,
            showModal: true,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //商品详情 减数量
  Gd_minus: function () {
    var that = this;
    var num = that.data.goodsDetails_num
    if (num > 1) {
      that.setData({
        goodsDetails_num: num - 1
      })
    }
  },
  //商品详情 加数量
  Gd_add: function () {
    var that = this;
    var num = that.data.goodsDetails_num
    that.setData({
      goodsDetails_num: num + 1
    })
  },
  //商品详情 加入购物车
  addCart_gd: function (e) {
    var that = this;
    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);
    that.addCart(spuId, num);//计算购物车数量
    that.setData({
      showModal: false,
    })
  },

  /**
  * 隐藏模态对话框
  */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    var openIdFlag = wx.getStorageSync('openId');     //用户openId获取
    var phoneFlag = wx.getStorageSync('phone');       //用户phone获取
    //判断openId是否存在
    if (openIdFlag != '') {
      that.setData({
        openId: openIdFlag
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }
    //判断手机号是否存在
    if (phoneFlag != '') {
      that.setData({
        phone: phoneFlag
      });
      that.gucl();                        //初始化购物车
    } else {
      that.setData({
        phone: ''
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {

    var that = this;
    var goodsDetails = that.data.goodsDetails;

    console.log(goodsDetails)

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: goodsDetails.name,
      // desc: '最具人气的小程序开发联盟!',
      path: 'pages/Zindex/Zindex?spuId=' + goodsDetails.spuId,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log("转发成功之后的回调")
        }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log("用户取消转发")
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log("转发失败")
        }
      },
    }
    // 来自页面内的按钮的转发
    　　if (options.from == 'button') {
      // 此处可以修改 shareObj 中的内容
        shareObj.path = 'pages/Zindex/Zindex?spuId=' + goodsDetails.spuId;
    　　}
    　　// 返回shareObj
    　　return shareObj;
  },
  //按钮获取用户信息
  getUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          wx.setStorageSync('userId', userInfo_.unionId);
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  }
})